<script>
import { add, batchDelete, page, update } from '@/api/questionBankCategory';
import { FilterMatchMode } from '@primevue/core/api';
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import SelectButton from 'primevue/selectbutton';
import { useToast } from 'primevue/usetoast';
import Dropdown from 'primevue/dropdown';

export default {
    components: {
        InputText,
        Button,
        SelectButton,
        Dropdown
    },
    data() {
        return {
            categories: [],
            category: {
                id: null,
                name: '',
                parentId: null,
                sort: null,
                status: null
            },
            statuses: [
                { label: '启用', value: 1 },
                { label: '禁用', value: 0 }
            ],
            selectedCategories: null,
            newCategoryDialog: false,
            editCategoryDialog: false,
            deleteCategoryDialog: false,
            deleteCategoriesDialog: false,
            submitted: false,
            loading: false,
            filters: {
                global: { value: null, matchMode: FilterMatchMode.CONTAINS }
            },
            pageSize: 10,
            pageNum: 1,
            totalRecords: 0,
            searchQuery: {
                id: null,
                name: null,
                parentId: null,
                status: null
            }
        };
    },
    mounted() {
        this.loadCategories();
    },
    methods: {
        async loadCategories() {
            this.loading = true;
            try {
                const response = await page({
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    ...this.searchQuery
                });

                if (response.code === 200) {
                    this.categories = response.data.list || [];
                    this.totalRecords = response.data.total || 0;
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载分类数据',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载分类数据',
                    life: 3000
                });
                console.error('加载分类失败:', error);
            } finally {
                this.loading = false;
            }
        },
        resetSearch() {
            this.searchQuery = {
                id: null,
                name: null,
                parentId: null,
                status: null
            };
            this.loadCategories();
        },
        onPage(event) {
            this.pageNum = event.page + 1;
            this.pageSize = event.rows;
            this.loadCategories();
        },
        onSort(event) {
            let sortField = event.sortField;
            let sortOrder = event.sortOrder;
            if (sortField) {
                this.categories.sort((a, b) => {
                    let result = 0;
                    if (a[sortField] < b[sortField]) {
                        result = -1;
                    } else if (a[sortField] > b[sortField]) {
                        result = 1;
                    }
                    return sortOrder === 1 ? result : -result;
                });
            }
        },

        performSearch() {
            this.pageNum = 1;
            this.pageSize = 10;
            this.loadCategories();
        },

        openNew() {
            this.category = {
                id: null,
                name: '',
                parentId: 0,
                sort: 0,
                status: 1
            };
            this.submitted = false;
            this.newCategoryDialog = true;
        },

        hideNewDialog() {
            this.newCategoryDialog = false;
            this.submitted = false;
            this.resetCategory();
        },

        editCategory(category) {
            this.category = { ...category };
            this.editCategoryDialog = true;
        },

        hideEditDialog() {
            this.editCategoryDialog = false;
            this.submitted = false;
            this.resetCategory();
        },

        resetCategory() {
            this.category = {
                id: null,
                name: '',
                parentId: 0,
                sort: 0,
                status: null
            };
        },

        async saveCategory() {
            this.submitted = true;

            if (!this.category.name?.trim()) {
                return;
            }

            try {
                this.loading = true;

                const isEdit = !!this.category.id;
                const response = isEdit ? await update(this.category) : await add(this.category);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: isEdit ? '分类已更新' : '分类已创建',
                        life: 3000
                    });

                    if (isEdit) {
                        this.editCategoryDialog = false;
                    } else {
                        this.newCategoryDialog = false;
                    }

                    this.resetCategory();

                    await this.loadCategories();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '保存分类失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '保存分类时出错',
                    life: 3000
                });
                console.error('保存分类失败:', error);
            } finally {
                this.loading = false;
            }
        },

        confirmDeleteCategory(category) {
            this.category = category;
            this.deleteCategoryDialog = true;
        },

        async deleteCategory() {
            try {
                this.loading = true;
                const response = await batchDelete([this.category.id]);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '分类已删除',
                        life: 3000
                    });
                    this.deleteCategoryDialog = false;

                    this.resetCategory();

                    this.loadCategories();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '删除分类失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '删除分类时出错',
                    life: 3000
                });
                console.error('删除分类失败:', error);
            } finally {
                this.loading = false;
                this.deleteCategoryDialog = false;
            }
        },

        confirmDeleteSelected() {
            this.deleteCategoriesDialog = true;
        },

        async deleteSelectedCategories() {
            try {
                this.loading = true;
                // 假设后端支持批量删除
                const ids = this.selectedCategories.map((cat) => cat.id);
                const response = await batchDelete(ids);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '选中的分类已删除',
                        life: 3000
                    });
                    this.selectedCategories = null;
                    this.deleteCategoriesDialog = false;
                    this.loadCategories();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '批量删除分类失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '批量删除分类时出错',
                    life: 3000
                });
                console.error('批量删除分类失败:', error);
            } finally {
                this.loading = false;
                this.deleteCategoriesDialog = false;
            }
        },

        exportCSV() {
            this.$refs.dt.exportCSV();
        },

        // 添加这些方法用于显示状态
        getStatusLabel(status) {
            switch (status) {
                case 0:
                    return '禁用';
                case 1:
                    return '启用';
                default:
                    return '未知';
            }
        },

        getStatusSeverity(status) {
            switch (status) {
                case 0:
                    return 'danger';
                case 1:
                    return 'success';
                default:
                    return 'info';
            }
        }
    },
    setup() {
        const toast = useToast();
        return { toast };
    }
};
</script>

<template>
    <div>
        <div class="card">
            <Toast />
            <Toolbar class="mb-6">
                <template #start>
                    <Button label="新增分类" icon="pi pi-plus" severity="secondary" class="mr-2" @click="openNew" />
                    <Button label="批量删除" icon="pi pi-trash" severity="secondary" @click="confirmDeleteSelected" :disabled="!selectedCategories || !selectedCategories.length" />
                </template>
                <template #end>
                    <Button label="导出" icon="pi pi-upload" severity="secondary" @click="exportCSV($event)" />
                </template>
            </Toolbar>
            <Toolbar>
                <template #start>
                    <InputText v-model="searchQuery.id" placeholder="Search by ID..." class="mr-2" />
                    <InputText v-model="searchQuery.parentId" placeholder="Search by ParenId..." class="mr-2" />
                    <InputText v-model="searchQuery.name" placeholder="Search by Name..." class="mr-2" />
                    <Dropdown v-model="searchQuery.status" :options="statuses" optionLabel="label" optionValue="value" placeholder="Select Status" class="mr-2" :showClear="true" />
                    <Button v-if="Object.values(searchQuery).some((value) => value !== null && value !== '')" label="重置" icon="pi pi-eraser" severity="info" @click="resetSearch" color="mr-2" />
                </template>
                <template #end>
                    <Button label="Search" icon="pi pi-search" @click="performSearch" />
                </template>
            </Toolbar>
            <DataTable
                v-model:selection="selectedCategories"
                :value="categories"
                dataKey="id"
                :paginator="true"
                :rows="pageSize"
                @sort="onSort($event)"
                lazy
                :totalRecords="totalRecords"
                :loading="loading"
                @page="onPage($event)"
                :filters="filters"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rowsPerPageOptions="[5, 10, 20, 50]"
                currentPageReportTemplate="显示 {first} 到 {last} 共 {totalRecords} 条记录"
            >
                <template #header>
                    <h4 class="m-0">题库分类管理</h4>
                </template>

                <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
                <Column field="id" header="ID" sortable="true" style="min-width: 5rem"></Column>
                <Column field="name" header="分类名称" sortable style="min-width: 16rem"></Column>
                <Column field="parentId" header="父id" sortable style="min-width: 20rem"></Column>
                <Column field="sort" header="排序" sortable style="min-width: 10rem"></Column>
                <Column field="status" header="状态" sortable>
                    <template #body="slotProps">
                        <Tag :severity="getStatusSeverity(slotProps.data.status)" :value="getStatusLabel(slotProps.data.status)" />
                    </template>
                </Column>
                <Column header="操作" style="min-width: 10rem">
                    <template #body="slotProps">
                        <Button icon="pi pi-pencil" outlined rounded class="mr-2" @click="editCategory(slotProps.data)" />
                        <Button icon="pi pi-trash" outlined rounded severity="danger" @click="confirmDeleteCategory(slotProps.data)" />
                    </template>
                </Column>
            </DataTable>
        </div>

        <Dialog v-model:visible="newCategoryDialog" :style="{ width: '450px' }" header="新增分类" :modal="true" class="p-fluid">
            <div class="flex flex-col gap-6">
                <div>
                    <label for="name" class="block font-bold mb-3">名称</label>
                    <InputText id="name" v-model.trim="category.name" required="true" autofocus :invalid="!category.name" fluid />
                    <small v-if="submitted && !category.name" class="text-red-500">名称是必须的</small>
                </div>
                <div>
                    <label for="parentId" class="block font-bold mb-3">父ID</label>
                    <InputNumber id="parentId" v-model="category.parentId" required="true" rows="3" cols="20" fluid />
                    <small v-if="submitted && !category.parentId" class="text-red-500">父ID是必须的</small>
                </div>
                <div>
                    <label for="sort" class="block font-bold mb-3">排序</label>
                    <InputNumber id="sort" v-model="category.sort" required="true" rows="3" cols="20" fluid />
                    <small v-if="submitted && category.sort == null" class="text-red-500">排序是必须的</small>
                </div>
                <div>
                    <label for="status" class="block font-bold mb-3">状态</label>
                    <SelectButton id="status" v-model="category.status" :options="statuses" optionLabel="label" optionValue="value" />
                </div>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="hideNewDialog" />
                <Button label="保存" icon="pi pi-check" @click="saveCategory" />
            </template>
        </Dialog>

        <Dialog v-model:visible="editCategoryDialog" :style="{ width: '450px' }" header="编辑分类" :modal="true" class="p-fluid">
            <div class="flex flex-col gap-6">
                <div>
                    <label for="edit-id" class="block font-bold mb-3">ID</label>
                    <InputText id="edit-id" disabled v-model.trim="category.id" fluid />
                </div>
                <div>
                    <label for="edit-name" class="block font-bold mb-3">名称</label>
                    <InputText id="edit-name" v-model.trim="category.name" required="true" autofocus :invalid="!category.name" fluid />
                    <small v-if="submitted && !category.name" class="text-red-500">名称是必须的</small>
                </div>
                <div>
                    <label for="edit-parentId" class="block font-bold mb-3">父ID</label>
                    <InputNumber id="edit-parentId" v-model="category.parentId" required="true" rows="3" cols="20" fluid />
                    <small v-if="submitted && !category.parentId" class="text-red-500">父ID是必须的</small>
                </div>
                <div>
                    <label for="edit-sort" class="block font-bold mb-3">排序</label>
                    <InputNumber id="edit-sort" v-model="category.sort" required="true" rows="3" cols="20" fluid />
                    <small v-if="submitted && category.sort == null" class="text-red-500">排序是必须的</small>
                </div>
                <div>
                    <label for="edit-status" class="block font-bold mb-3">状态</label>
                    <SelectButton id="edit-status" v-model="category.status" :options="statuses" optionLabel="label" optionValue="value" />
                </div>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="hideEditDialog" />
                <Button label="保存" icon="pi pi-check" @click="saveCategory" />
            </template>
        </Dialog>

        <Dialog v-model:visible="deleteCategoryDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span v-if="category"
                    >确定要删除分类 <b>{{ category.name }}</b> 吗？</span
                >
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteCategoryDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteCategory" />
            </template>
        </Dialog>

        <Dialog v-model:visible="deleteCategoriesDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span>确定要删除选中的分类吗？</span>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteCategoriesDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteSelectedCategories" />
            </template>
        </Dialog>
    </div>
</template>
